package info.thereisonlywe.onenesspathfinder.ui;

import info.thereisonlywe.core.font.FontLibrary;
import info.thereisonlywe.core.project.ProjectConstants;
import info.thereisonlywe.core.project.ProjectLocalization;
import info.thereisonlywe.core.ui.swing.extensions.table.EmptyCellEditor;
import info.thereisonlywe.core.ui.swing.extensions.table.TextAreaRenderer;
import info.thereisonlywe.quran.bookmark.QuranicBookmarkManager;
import info.thereisonlywe.quran.text.QuranicTextList;

import java.awt.Color;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.ToolTipManager;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;

public class BookmarkPane extends JScrollPane {

	private final JTable table_Bookmark = new JTable()
	{
		@Override
		public TableCellRenderer getCellRenderer(int row, int column)
		{
			return getColumnModel().getColumn(0).getCellRenderer();
		}

	};

	private final JPopupMenu popupMenu_Bookmark = new JPopupMenu();

	public BookmarkPane()
	{
		super();
		initComponents();
		initPopupItems();
		initListeners();
	}

	public JTable getTable()
	{
		return table_Bookmark;
	}

	public JPopupMenu getPopupMenu()
	{
		return popupMenu_Bookmark;
	}

	private void initPopupItems()
	{

		JMenuItem item;

		item = new JMenuItem(ProjectLocalization.getString(
				ProjectConstants.CORE_PROJECT, "Save"));
		item.setMargin(UIConstants.MARGIN);
		item.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				SaveBookmarksDialog.showDialog(UIDelegate.BookmarkPaneHook
						.getSelected());
			}
		});

		popupMenu_Bookmark.add(item);

		item = new JMenuItem(ProjectLocalization.getString(
				ProjectConstants.CORE_PROJECT, "Rename"));
		item.setMargin(UIConstants.MARGIN);
		item.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				UIDelegate.setOpenDialog(true);
				String name = JOptionPane.showInputDialog(null,
						ProjectLocalization.getString(
								ProjectConstants.ONENESS_PATHFINDER_PROJECT,
								"Bookmark.Comment"),
						ProjectLocalization.getString(
								ProjectConstants.ONENESS_PATHFINDER_PROJECT,
								"RenameBookmarks"), JOptionPane.PLAIN_MESSAGE);
				UIDelegate.BookmarkPaneHook.getBookmarkList().addBookmarks(
						UIDelegate.BookmarkPaneHook.getSelected(), name);
				UIDelegate.BookmarkPaneHook.refresh();
				UIDelegate.setOpenDialog(false);
			}
		});

		popupMenu_Bookmark.add(item);

		item = new JMenuItem(ProjectLocalization.getString(
				ProjectConstants.CORE_PROJECT, "Delete"));
		item.setAccelerator(KeyStroke.getKeyStroke("DELETE"));
		item.setMargin(UIConstants.MARGIN);
		item.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				UIDelegate.BookmarkPaneHook.removeSelectedBookmarks();
			}
		});

		popupMenu_Bookmark.add(item);
		popupMenu_Bookmark.addSeparator();

		item = new JMenuItem(ProjectLocalization.getString(
				ProjectConstants.CORE_PROJECT, "SelectAll"));
		item.setAccelerator(KeyStroke.getKeyStroke("ctrl A"));
		item.setMargin(UIConstants.MARGIN);
		item.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				UIDelegate.BookmarkPaneHook.selectAll();
			}
		});

		popupMenu_Bookmark.add(item);

		item = new JMenuItem(ProjectLocalization.getString(
				ProjectConstants.CORE_PROJECT, "LoadFromFile"));
		item.setMargin(UIConstants.MARGIN);
		item.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				final String[] bookmarkNames = QuranicBookmarkManager
						.getExistingBookmarkListNames();
				if (bookmarkNames == null || bookmarkNames.length == 0)
				{
					UIDelegate.showErrorDialog("NoBookmarkListFound");
					return;
				}
				UIDelegate.setOpenDialog(true);
				String n = (String) JOptionPane.showInputDialog(null, null,
						"Oneness Pathfinder", JOptionPane.PLAIN_MESSAGE, null,
						bookmarkNames, bookmarkNames[0]);
				UIDelegate.setOpenDialog(false);
				if (n != null && !n.isEmpty())
				{
					UIDelegate.BookmarkPaneHook
							.getBookmarkList()
							.loadBookmarks(
									new File(
											QuranicBookmarkManager.BOOKMARKS_PATH
													+ File.separator
													+ n
													+ ".qbm"));
					UIDelegate.BookmarkPaneHook.refresh();

				}
			}
		});

		popupMenu_Bookmark.add(item);
	}

	private void initListeners()
	{

		table_Bookmark.addMouseListener(new MouseAdapter()
		{
			@Override
			public void mouseClicked(MouseEvent e)
			{
				if (e.getClickCount() == 2)
				{
					int indices[] = table_Bookmark.getSelectedRows();
					if (indices.length == 1)
					{
						UIDelegate.seekToVerse(UIDelegate.BookmarkPaneHook
								.getBookmarkList().getBookmarkPosition(
										indices[0]));
					}
				}
			}

			@Override
			public void mousePressed(MouseEvent e)
			{
				if (e.isPopupTrigger())
				{
					refreshPopup();
					popupMenu_Bookmark.show(e.getComponent(), e.getX(),
							e.getY());
				}
			}

			@Override
			public void mouseReleased(MouseEvent e)
			{
				if (e.isPopupTrigger())
				{
					refreshPopup();
					popupMenu_Bookmark.show(e.getComponent(), e.getX(),
							e.getY());
				}
			}
		});

		addMouseListener(new MouseAdapter()
		{
			@Override
			public void mousePressed(MouseEvent e)
			{
				if (e.isPopupTrigger())
				{
					refreshPopup();
					popupMenu_Bookmark.show(e.getComponent(), e.getX(),
							e.getY());
				}
			}

			@Override
			public void mouseReleased(MouseEvent e)
			{
				if (e.isPopupTrigger())
				{
					refreshPopup();
					popupMenu_Bookmark.show(e.getComponent(), e.getX(),
							e.getY());
				}
			}
		});

	}

	private void initComponents()
	{
		table_Bookmark.setTableHeader(null);
		table_Bookmark
				.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		TableModel model = new TableModel();
		model.addTableModelListener(new TableListener());
		table_Bookmark.setForeground(Color.black);
		table_Bookmark.setSelectionBackground(Color.LIGHT_GRAY);
		table_Bookmark.setSelectionForeground(Color.black);
		table_Bookmark.setModel(model);
		table_Bookmark.getColumnModel().getColumn(0)
				.setCellRenderer(new TableRenderer());
		table_Bookmark.getColumnModel().getColumn(0)
				.setCellEditor(new EmptyCellEditor());
		setBorder(BorderFactory.createTitledBorder(BorderFactory
				.createMatteBorder(3, 3, 3, 3, Color.DARK_GRAY),
				ProjectLocalization.getString(ProjectConstants.CORE_PROJECT,
						"Bookmarks"), 0, TitledBorder.BELOW_TOP, FontLibrary
						.get(FontLibrary.DROID_SANS, Font.BOLD, 12),
				Color.DARK_GRAY));
		ToolTipManager.sharedInstance().unregisterComponent(table_Bookmark);
		setViewportView(table_Bookmark);

		table_Bookmark.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
				.put(KeyStroke.getKeyStroke("ENTER"), "none");
		table_Bookmark.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
				.put(KeyStroke.getKeyStroke("TAB"), "none");
		table_Bookmark.getActionMap().put("none", new AbstractAction()
		{

			@Override
			public void actionPerformed(ActionEvent e)
			{
			}
		});
	}

	private void refreshPopup()
	{
		if (UIDelegate.BookmarkPaneHook.getBookmarkList()
				.getNumberOfBookmarks() > 0)
		{
			popupMenu_Bookmark.getComponent(4).setEnabled(true);
			if (UIDelegate.BookmarkPaneHook.getSelected().length > 0)
			{
				popupMenu_Bookmark.getComponent(0).setEnabled(true);
				popupMenu_Bookmark.getComponent(1).setEnabled(true);
				popupMenu_Bookmark.getComponent(2).setEnabled(true);
			}
			else
			{
				popupMenu_Bookmark.getComponent(0).setEnabled(false);
				popupMenu_Bookmark.getComponent(1).setEnabled(false);
				popupMenu_Bookmark.getComponent(2).setEnabled(false);
			}

		}

		else
		{
			popupMenu_Bookmark.getComponent(4).setEnabled(false);
			popupMenu_Bookmark.getComponent(0).setEnabled(false);
			popupMenu_Bookmark.getComponent(1).setEnabled(false);
			popupMenu_Bookmark.getComponent(2).setEnabled(false);
		}

		String[] bookmarkNames = QuranicBookmarkManager
				.getExistingBookmarkListNames();
		if (bookmarkNames == null || bookmarkNames.length == 0)
		{
			popupMenu_Bookmark.getComponent(5).setEnabled(false);
		}
		else popupMenu_Bookmark.getComponent(5).setEnabled(true);
		bookmarkNames = null;
	}

	private class TableListener implements TableModelListener {
		@Override
		public void tableChanged(TableModelEvent te)
		{
			// ComponentOrientation co;
			// int pref = QuranicTextList.getPreferred();
			// if (pref == -1 || QuranicTextList.getText(pref).isRTL())
			// {
			// co = ComponentOrientation.RIGHT_TO_LEFT;
			// }
			// else co = ComponentOrientation.LEFT_TO_RIGHT;
			// if (!getComponentOrientation().equals(co))
			// setComponentOrientation(co);
		}
	}

	public class TableModel extends AbstractTableModel {

		public TableModel()
		{
		}

		@Override
		public int getRowCount()
		{
			return UIDelegate.BookmarkPaneHook.getBookmarkList()
					.getNumberOfBookmarks();
		}

		@Override
		public int getColumnCount()
		{
			return 1;
		}

		@Override
		public Object getValueAt(int rowIndex, int columnIndex)
		{
			return UIDelegate.BookmarkPaneHook.getBookmarkList()
					.getBookmarkInfo(rowIndex);
		}

		@Override
		public Class<?> getColumnClass(int columnIndex)
		{
			return String.class;
		}
	}

	public static class TableRenderer extends TextAreaRenderer {

		private static final TitledBorder border = BorderFactory
				.createTitledBorder(
						BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),
						"0", 0, TitledBorder.TOP,
						FontLibrary.get(FontLibrary.DROID_SANS, Font.BOLD, 12),
						new Color(73, 43, 98));

		public TableRenderer()
		{
			super();
		}

		@Override
		public Component getTableCellRendererComponent(JTable table,
				Object obj, boolean isSelected, boolean hasFocus, int row,
				int column)
		{
			adaptee.getTableCellRendererComponent(table, obj, isSelected,
					hasFocus, row, column);
			int pref = QuranicTextList.getPreferred();
			if (pref == -1 || QuranicTextList.getText(pref).isRTL()) setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
			else setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
			setForeground(adaptee.getForeground());
			setBackground(adaptee.getBackground());
			border.setTitle(UIDelegate.BookmarkPaneHook.getBookmarkList()
					.getBookmarkPosition(row).toNotationString()
					+ "");
			border.setTitleJustification(pref == -1
					|| QuranicTextList.getText(pref).isRTL() ? Integer
					.valueOf(TitledBorder.RIGHT) : Integer
					.valueOf(TitledBorder.LEFT));
			setBorder(border);
			setFont(adaptee.getFont());
			setText(adaptee.getText());
			TableColumnModel columnModel = table.getColumnModel();
			setSize(columnModel.getColumn(column).getWidth(), 100000);
			int height_wanted = (int) getPreferredSize().getHeight();
			addSize(table, row, column, height_wanted);
			height_wanted = findTotalMaximumRowSize(table, row);
			if (height_wanted != table.getRowHeight(row))
			{
				table.setRowHeight(row, height_wanted);
			}
			return this;
		}

		@Override
		public void invalidate()
		{
		}

		@Override
		public void repaint()
		{
		}
	}

}
